package com.riki.riki_push_example.protecter.handler;


/*
 * Author : LiJiqqi
 * Date : 2021/1/30
 */

import android.app.Activity;
import android.util.Log;


import com.riki.riki_push_example.protecter.plugin.AndroidInfoUploader;

import java.io.PrintWriter;
import java.io.StringWriter;


public class DefaultActivityExceptionHandler extends ActivityExceptionHandler {
    static private final String TAG = "Exception_Handler:";
    private final String slash = "------------------";
    private final String pattern = "====================注意，注意，异常骑脸！！！===================";


    //启动类的类名
    // * com.example.riki.MainActivity
    private final String launchActivityName = ".MainActivity";
    ///

    /**
     *[protectUIThread]和[protectActivityStart]异常将会调用这个方法
     * 
     * {@link ActivityStartProtect}
     * {@link UIThreadProtect}
     */
    
    @Override
    public void onException(Activity activity, Exception e) {
        Log.i(TAG,"==========Activity(UI thread) 发生了一个异常=========");
        logPattern();
        if(e != null){
            Log.d(TAG,""+e.getMessage());
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            AndroidInfoUploader.getInstance().sinker.success("Android异常: " + sw.toString() );
        }
        if(activity != null){
            if(activity.getLocalClassName().contains(launchActivityName)){
                //如果是启动activity，则不finish，否则整个应用无法启动
                // * 虽然这里未做 finish() 以保证应用的启动，但是启动类(activity)的异常还是不应该出现的

            }else{
                activity.finish();
            }
        }
        logPattern();
    }

    /*
    * 命中有问题，暂时注释掉
    * */
//    private void getLaunchActivity(Activity activity){
//        Intent resolveIntent = new Intent(Intent.ACTION_MAIN,null);
//        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//        List<ResolveInfo> appInfos = activity.getPackageManager().queryIntentActivities(resolveIntent,0);
//        for(ResolveInfo info : appInfos){
//            String activityName = info.activityInfo.name;
//            Log.i("test123",activityName);
//        }
//        
//    }
    

   
    /**
     *子线程异常会调用此方法 ,
     * 注意，此方法内的线程切换
     * {@link ChildThreadProtect}
     */
    @Override
    public void onChildThreadException(Thread t, Throwable e) {
        Log.d(TAG, slash+TAG+slash);
        Log.i(TAG,"==========子线程 发生了一个异常=========");
        Log.d(TAG,t.getName());
        e.printStackTrace();
        Log.d(TAG, slash+TAG+slash);
        logPattern();
    }

    private void logPattern(){
        Log.i(TAG,pattern);
        Log.i(TAG,pattern);
        Log.i(TAG,pattern);
        Log.i(TAG,pattern);
        Log.i(TAG,pattern);
    }
}
